#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dateutil
from flask import jsonify, request
from flask_restful import Resource
from datetime import datetime
from dateutil.relativedelta import relativedelta
import calendar
from utility.error_code import error_code
from utility.odoo_manager import OdooManager
import logging
from utility import tools


FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class UpperDataAPI(Resource):
    """
    获取首页上部统计数据接口,返回：建档人数,高危人数,本院建档人数,复诊率,今日建档人数
    :request: get
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            odoo = OdooManager().get_instance()
            # 建档人数
            archivesTotal = odoo.env['res.archives'].search_count([])
            # 高危人数
            highRiskTotal = odoo.env['res.archives'].search_count(
                [('max_gwys', 'in', ['1', '2', '3', '4'])])
            # 本院建档人数
            ourHospitalArchives = odoo.env['res.archives'].search_count([('jd_sfby', '=', '1')])
            # 复诊率
            BackCount = 0.0
            SumCount = 0.0
            Resuts = odoo.env['res.archives'].search_read('', ['jd_date','sccjrq'], '', '')
            if Resuts:
                for Result in Resuts:
                    SumCount = SumCount + 1
                    if Result['jd_date'] != Result['sccjrq']:
                        BackCount = BackCount + 1
            returnVisit = 100.0
            if SumCount != 0:
                returnVisit = round((BackCount * 100.0 / SumCount), 2)
            # 今日建档人数
            todayArchives = odoo.env['res.archives'].search_count([('jd_date', '=', str(datetime.today()))])
            return jsonify({
                'code': 0,
                'data': {
                    'archivesTotal': archivesTotal,
                    'highRiskTotal': highRiskTotal,
                    'ourHospitalArchives': ourHospitalArchives,
                    'returnVisit': returnVisit,
                    'todayArchives': todayArchives
                },
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class ArchivesAreaAPI(Resource):
    """
    档案区域分布统计,返回：排名(只显示前五名),区域ID,区域名称,区域人数
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            odoo = OdooManager().get_instance()
            dataResults = odoo.env['res.archives'].read_group([('status', '=', '0')],  # 过滤条件
                                                         ['mq_jt_county', 'mq_sfz:count'],  # 返回字段
                                                         ['mq_jt_county'],  # 分组字段
                                                         lazy=False)
            k = 1
            datas = []
            if dataResults:
                for dataResult in dataResults:
                    if k < 6:
                        datas.append(
                            {
                                'rankNo': k,
                                'regionId': dataResult['mq_jt_county'][0],
                                'regionName': dataResult['mq_jt_county'][1],
                                'totals': dataResult['__count'],
                            })
                        k = k + 1
                    else:
                        break
            return jsonify({
                'code': 0,
                'data': datas,
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class FollowUpTaskAPI(Resource):
    """
    查询随访任务列表
    :request: post
    :returns: json string
    """

    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            isAsc = params.get('isAsc')  # 排序的方向,示例值(asc,desc)
            orderByColumn = params.get('orderByColumn')  # 排序列
            pageNum = params.get('pageNum')  # 当前页数
            pageSize = params.get('pageSize')  # 分页大小
            rows = []
            Resuts = odoo.env['inspection.follow.recall'] .search_read([],
                             ['archives_id', 'create_date', 'id', 'start_time', 'end_time', 'user_id', 'follow_type',
                              'follow_data_type','follow_yz', 'name', 'state'],
                             # 档案ID,创建时间,随访任务ID,    随访发起时间,随访完成时间,随访任务编号,   随访方式,随访任务类型,随访孕周    随访人,随访状态
                             offset=(int(pageNum) - 1) * int(pageSize),
                             limit=int(pageSize))
            if isAsc == 'asc' and orderByColumn != '':
                Resuts = Resuts.sorted(orderByColumn, reverse=False)
            elif isAsc == 'desc' and orderByColumn != '':
                Resuts = Resuts.sorted(orderByColumn, reverse=True)
            if Resuts:
                for Resut in Resuts:
                    DangAn = odoo.env['res.archives'].search_read([('id', '=', Resut['archives_id'][0])],
                                                                  ['mq_xm', 'max_gwys', 'mq_sfz'],
                                                                  # 孕产妇姓名,高危颜色,档案身份证ID
                                                                  '',
                                                                  '')
                    rows.append(
                        {
                            'archivesId': Resut['archives_id'][0],
                            'cfMqXm': DangAn[0]['mq_xm'],
                            'createTime': Resut['create_date'],
                            'gwColorCode': DangAn[0]['max_gwys'],
                            'id': Resut['id'],
                            'sfFqSj': Resut['start_time'],
                            'sfWcSj': Resut['end_time'],
                            'sfRwBh': Resut['user_id'][0],
                            'sfRwFs': Resut['follow_type'],
                            'sfRwLx': Resut['follow_data_type'],
                            'sfRwYz': Resut['follow_yz'],
                            'sfr': Resut['name'],
                            'sfz': DangAn[0]['mq_sfz'],
                            'status': Resut['state']
                        })
            total = odoo.env['inspection.follow.recall'].search_count([])
            return jsonify({
                'code': 0,
                'msg': 'success',
                'rows': rows,
                'total': total
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class DeliverAPI(Resource):
    """
    查询分娩统计,返回：labourStatistics分娩人数集合,normalLabourStatistics顺产人数集合,
                      planingLabourStatistics刨宫产人数集合,dates
    :request: post
    :returns: json string
    """

    def post(self):
        try:
            params = tools.get_params(request)
            queryType = params.get('queryType')
            labourStatistics = []
            normalLabourStatistics = []
            planingLabourStatistics = []
            dates = []
            num = 6  # 近6个月
            if queryType == '2':  # 近1年
                num = 12
            odoo = OdooManager().get_instance()
            start1 = str(datetime.today().date())[0:7] + '-01'
            end1 = str(datetime.today().date())
            temp1 = odoo.env['birth.record.cloud'].search_count(
                [('cf_fmsj', '<=', end1), ('cf_fmsj', '>=', start1)])
            labourStatistics.append(temp1)
            temp2 = odoo.env['birth.record.cloud'].search_count(
                [('cf_fmsj', '<=', end1), ('cf_fmsj', '>=', start1), ('cf_fmfs', '=', '1')])
            normalLabourStatistics.append(temp2)
            temp3 = odoo.env['birth.record.cloud'].search_count(
                [('cf_fmsj', '<=', end1), ('cf_fmsj', '>=', start1), ('cf_fmfs', '=', '2')])
            planingLabourStatistics.append(temp3)
            dates.append(datetime.today().date().month)
            for i in range(1, num):
                tempDate = datetime.today() + relativedelta(months=-i)
                tempStart = str(tempDate.date())[0:7] + '-01'
                monthCountDay = calendar.monthrange(tempDate.year, tempDate.month)[1]
                tempEnd = str(tempDate.date())[0:7] + '-' + str(monthCountDay)
                tempLabourStatistics = odoo.env['birth.record.cloud'].search_count(
                    [('cf_fmsj', '<=', tempEnd), ('cf_fmsj', '>=', tempStart)])
                labourStatistics.append(tempLabourStatistics)
                tempNormalLabourStatistics = odoo.env['birth.record.cloud'].search_count(
                    [('cf_fmsj', '<=', tempEnd), ('cf_fmsj', '>=', tempStart), ('cf_fmfs', '=', '1')])
                normalLabourStatistics.append(tempNormalLabourStatistics)
                tempPlaningLabourStatistics = odoo.env['birth.record.cloud'].search_count(
                    [('cf_fmsj', '<=', tempEnd), ('cf_fmsj', '>=', tempStart), ('cf_fmfs', '=', '2')])
                planingLabourStatistics.append(tempPlaningLabourStatistics)
                dates.append(tempDate.month)
            return jsonify({
                'code': 0,
                'data': {
                    'labourStatistics': labourStatistics,
                    'normalLabourStatistics': normalLabourStatistics,
                    'planingLabourStatistics': planingLabourStatistics,
                    'dates': dates
                },
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class HighRiskAPI(Resource):
    """
    高危分布图表,返回：gwColorCode高危颜色,totals高危人数
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            odoo = OdooManager().get_instance()
            data = []
            CountLv = odoo.env['res.archives'].search_count([('max_gwys', '=', '0'), ('status', '=', '0')])
            data.append({'gwColorCode': '0', "totals": CountLv, 'gwColor': '绿色'})
            CountHuang = odoo.env['res.archives'].search_count([('max_gwys', '=', '1'), ('status', '=', '0')])
            data.append({'gwColorCode': '1', "totals": CountHuang, 'gwColor': '黄色'})
            CountCheng = odoo.env['res.archives'].search_count([('max_gwys', '=', '2'), ('status', '=', '0')])
            data.append({'gwColorCode': '2', "totals": CountCheng, 'gwColor': '橙色'})
            CountRed = odoo.env['res.archives'].search_count([('max_gwys', '=', '3'), ('status', '=', '0')])
            data.append({'gwColorCode': '3', "totals": CountRed, 'gwColor': '红色'})
            CountZhi = odoo.env['res.archives'].search_count(
                [('max_gwys', 'in', ['4', '5', '6', '7']), ('status', '=', '0')])
            data.append({'gwColorCode': '4', "totals": CountZhi, 'gwColor': '紫色'})
            return jsonify({
                'code': 0,
                'data': data,
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class ToDoAPI(Resource):
    """
    随访与访视待办统计数据
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            odoo = OdooManager().get_instance()
            # 总数量
            totals = odoo.env['inspection.follow.recall'].search_count([('state', '=', '1')])
            # 高危随访数量
            gwsf_total = odoo.env['inspection.follow.recall'].search_count(
                [('follow_data_type', '=', '0'), ('state', '=', '1')])
            # 产后随访数量
            chsf_total = odoo.env['inspection.follow.recall'].search_count(
                [('follow_data_type', '=', '1'), ('state', '=', '1')])
            # 高危风险筛查随访数量
            gwfxscsf_total = odoo.env['inspection.follow.recall'].search_count(
                [('state', '=', '1'), ('follow_data_type', 'in', ['2', '3', '4'])])
            other_total = totals - gwsf_total - chsf_total - gwfxscsf_total
            return jsonify({
                'code': 0,
                'data': {
                    'gwsf_total': gwsf_total,
                    'chsf_total': chsf_total,
                    'gwfxscsf_total': gwfxscsf_total,
                    'other_total': other_total,
                    'totals': totals
                },
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class NoticeAPI(Resource):
    """
    获取通知公告列表,返回:创建人,创建时间,公告ID,公告标题,公告内容,公告类型,状态,更新人,更新时间
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            odoo = OdooManager().get_instance()
            total = odoo.env['res.announcement'].search_count([('id', '>', 0)])
            notes = odoo.env['res.announcement'].search_read('', ['create_uid', 'create_date', 'id', 'name', 'content',
                                                                  'type', 'active', 'write_uid', 'write_date'], '', '')
            rows = []
            if notes:
                for note in notes:
                    rows.append(
                        {
                            "createBy": note['create_uid'][0],
                            "createTime": note['create_date'],
                            "noticeId": note['id'],
                            "noticeTitle": note['name'],
                            "noticeContent": note['content'],
                            "noticeType": note['type'],
                            "status": note['active'],
                            "updateBy": note['write_uid'][0],
                            "updateTime": note['write_date'],
                        })
            return jsonify({
                'code': 0,
                'msg': 'success',
                'rows': rows,
                'total': total
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})
